<?php

class FeatureBehavior extends ModelBehavior
{
	var $defaults = array('limit'=>false,'featureField'=>'is_featured');
	
	var $_settings = array();
	
	/*featureHistory Model instance*/
	var $FeatureHistory = null;
	function setup($model,$config=array())
	{
		$this->_settings[$model->alias] = am($this->defaults,$config);
		if($model->hasField($this->_settings[$model->alias]['featureField'])==false && cr('debug')>1)
		{
			trigger_error(sprintf("No field %s found in model %s for feature behavior",$this->_settings[$model->alias]['featureField'],$model->alias),E_USER_WARNING);
		}
		if(!is_object($this->FeatureHistory) || !is_a($this->FeatureHistory,'AppModel'))
		{
			$this->FeatureHistory = cri('FeatureHistory');			
		}
	}
	/**
	 * set as featured
	 * @param $model
	 * @param $id
	 */
	function makeFeatured($model,$id)
	{
		//$featureField = null;
		//$limit;
		extract($this->_settings[$model->alias]);
		$totalCount = $model->find('count',array('conditions'=>array($featureField => 1),'recursive'=>-1));
		if(is_numeric($limit) &&   $totalCount >= $limit)
		{
			$diff = ($totalCount - $limit)+1;
			$lastFeaturedIds = $this->FeatureHistory->find('list',array('conditions'=>array('entity'=>$model->alias,'status'=>FeatureHistory::ACTIVE),'order'=>'created ASC','limit'=>$diff,'fields'=>array('entity_id')));
			if($lastFeaturedIds)
			{
				foreach($lastFeaturedIds as $lastFeaturedId)
				{
					$this->removeFeatured($model,$lastFeaturedId);
				}
			}
		}
		$model->id = $id;
		if($model->saveField($featureField,1))
		{
			//insert in history table.
			$this->FeatureHistory->addToActive($model->alias,$id);
		}
	}
	
	function removeFeatured($model,$id)
	{
		extract($this->_settings[$model->alias]);
		$model->id = $id;
		if($model->saveField($featureField,0))
		{
			$this->FeatureHistory->addToArchive($model->alias,$id);
		}	
	}
	
	function getFeatureArchived($model,$limit=3)
	{
		$archived = $this->FeatureHistory->find('list',array('conditions'=>array('entity'=>$model->alias,'status'=>FeatureHistory::ARCHIVED),'fields'=>array('entity_id'),'limit'=>$limit,'order'=>array('created DESC')));	
		return $archived;
	}
	
	function isFeatured($model,$id)
	{
		return $this->FeatureHistory->hasAny(array('entity'=>$model->alias,'entity_id'=>$id,'status'=>FeatureHistory::ACTIVE));
	}
	
	function getLastFeatured($model,$limit=1)
	{
		return $this->FeatureHistory->find('list',array('conditions'=>array('entity'=>$model->alias,'status'=>FeatureHistory::ACTIVE),'limit'=>$limit,'order'=>"created desc",'fields'=>array('entity_id')));
	}
	
}